package com.edu.learning.concurrent;

import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.lang3.Validate;
import org.springframework.lang.Nullable;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * @author ll
 * @Date 2017/10/31 19:47
 */
public class ThreadPoolUtil {

    public static boolean gracefulShutdown(@Nullable ExecutorService threadPool, int shutdownTimeoutMills) {
        return threadPool != null
                ? MoreExecutors.shutdownAndAwaitTermination(threadPool, shutdownTimeoutMills, TimeUnit.MILLISECONDS)
                : true;
    }

    public static boolean gracefulShutdown(@Nullable ExecutorService threadPool, int shutdownTimeout, TimeUnit timeUnit) {
        return threadPool != null
                ? MoreExecutors.shutdownAndAwaitTermination(threadPool, shutdownTimeout, timeUnit)
                : true;
    }

    public static ThreadFactory buildThreadFactory(String threadNamePrefix) {
        Validate.notNull(threadNamePrefix);
        return new ThreadFactoryBuilder().setNameFormat(threadNamePrefix + "-%d").build();
    }

    public static ThreadFactory buildThreadFactory(@Nullable String threadNamePrefix, @Nullable boolean daemon) {
        return new ThreadFactoryBuilder().setNameFormat(threadNamePrefix + "-%d").setDaemon(daemon).build();
    }

    public static Runnable safeRunnable(@Nullable Runnable runnable) {
        return new SafeRunnable(runnable);
    }

    private static class SafeRunnable implements Runnable {
        private Runnable runnable;

        public SafeRunnable(Runnable runnable) {
            Validate.notNull(runnable);
            this.runnable = runnable;
        }

        @Override
        public void run() {
            try {
                runnable.run();
            } catch (Exception e) {
                System.err.println("Unexpected error occurred in task" + e);
            }
        }
    }
}
